#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
import random
from collections import OrderedDict

import AIManage

class WeightAI(AIManage.AIManage):
    def sendCard(self):
        try:
            if (AIManage.AIManage.sendCard(self) == False) : return
            
            selectCardIndex = self.selectSendCard()
            card = self.m_rgCards.pop(selectCardIndex)
            
            self.m_rgSendCards.append(card)
            self.m_dicSendCards[card] = self.m_nPlayerIndex
            message = OrderedDict()
            message[AIManage.KEY_MESSAGE_TYPE] = AIManage.MessageType.MESSAGE_GAME_PLAY
            message[AIManage.KEY_ACTION_TYPE] = AIManage.ActionType.ACTION_TYPE_SEND_A_CARD
            message[AIManage.KEY_PLAYER_INDEX] = self.m_nPlayerIndex
            message[AIManage.KEY_SEND_CARD] = card
            message[AIManage.KEY_IS_AI] = True
            message[AIManage.KEY_IS_TEMP] = self.m_bIsTemp
            
#            print "Player%d send Card %d" % (self.m_nPlayerIndex, card)
            AIManage.AIManage.sendCardMessageToOpponents(self, message)

        except Exception,e:
            print "error:", e

    def takeGroup(self):
        try:
            nGroup = self.selectTakeGroup()
            
            message = OrderedDict()
            message[AIManage.KEY_MESSAGE_TYPE] = AIManage.MessageType.MESSAGE_GAME_PLAY
            message[AIManage.KEY_ACTION_TYPE] = AIManage.ActionType.ACTION_TYPE_TAKE_A_GROUP
            message[AIManage.KEY_PLAYER_INDEX] = self.m_nPlayerIndex
            message[AIManage.KEY_TAKE_GROUP] = nGroup
            message[AIManage.KEY_IS_AI] = True
            message[AIManage.KEY_IS_TEMP] = self.m_bIsTemp
            
            strJsonMessage = json.dumps(message)
            strGameMessage = self.m_gameManage.receiveAMessage(strJsonMessage)
            for opponent in self.m_opponents:
                opponent.sendGameMessage(strGameMessage)
    
            self.getMessage(strGameMessage)
        except Exception,e:
            print "error:", e

    def selectSendCard(self):
        try:
            print "self.m_rgPublicCardsGroup : ", self.m_rgPublicCardsGroup
            
            rgCardHeads = []
        
            FACTOR = 10
        
            i = 0
            while i < 4:
                count = len(self.m_rgPublicCardsGroup[i])
                rgCardHeads.append(self.m_rgPublicCardsGroup[i][count - 1])
                i += 1
    
            rgCardHeads.sort()
    
            dicCardWeight = {}
        
            i = 0
            while i < len(self.m_rgCards):
                card = self.m_rgCards[i]
                if card < rgCardHeads[0]:
                    dicCardWeight[i] = card - 104
                    i += 1
                    continue
                else:
                    head = rgCardHeads[0]
                    nextHead = rgCardHeads[1]
                    count = len(self.m_rgPublicCardsGroup[0])
                    j = 0
                    while (j < len(rgCardHeads) - 1) and (card > rgCardHeads[j + 1]):
                        j += 1
                        head = rgCardHeads[j]
                        if j == len(rgCardHeads) - 1:
                            nextHead = 105
                        else:
                            nextHead = rgCardHeads[j + 1]
                        count = len(self.m_rgPublicCardsGroup[j])

                    dicCardWeight[i] =  (nextHead - card) / (card - head) * (4.5 - count)
                i += 1

            return sorted(dicCardWeight.items(), key = lambda x:x[1], reverse = True)[0][0]
    
        except Exception,e:
            print "error:", e

    def selectTakeGroup(self):
        try:
            minScore = 9999
            minGroup = -1
        
            i = 0
            while i < AIManage.CARD_GROUP_COUNT:
                scoreSum = 0
                for card in self.m_rgPublicCardsGroup[i]:
                    score = self.m_gameManage.getCardScore(card)
                    scoreSum += score
                    print "group %d score %d" % (i, scoreSum)
                if scoreSum < minScore:
                    minScore = scoreSum
                    minGroup = i
                i += 1
                    
            return minGroup
        
        except Exception,e:
            print "error:", e
